package servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utility.UserSession;

/**
 * Servlet implementation class ValidateUser
 */
public class ValidateUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ValidateUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		boolean loginResult = UserSession.validateUser(userName, password);
		String userID = UserSession.getUserID();
		if(loginResult)
		{
       	 request.setAttribute("message", "Welcome back "+userName+"!!");
       	try {
       		int score = UserSession.getRewardpoints();
			request.setAttribute("points", score);
			request.getSession().setAttribute("Score", score);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			request.getSession().setAttribute("userID", userID);
			RequestDispatcher RequestDispatcherObj =request.getRequestDispatcher("/view/UserHome.jsp");
            RequestDispatcherObj.forward(request, response);
		}
		else
		{
			request.setAttribute("message", "Invalid Login. Please try again");
			RequestDispatcher RequestDispatcherObj =request.getRequestDispatcher("/view/Login.jsp");
            RequestDispatcherObj.forward(request, response);
		}
	}

}
